package com.VolunteerPlatform.Service.UtilityService;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by DoveXL on 2018/12/10.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WriteExcelService {


    public void CreateTeamInfoExcel(List<Map<String,String>> TeamList,String filename,String[] ChineseName,String[] FieldName)throws IOException
    {
        //导出错误文件的函数
        //String[] title={"单位名称","负责人","负责人联系方式","错误信息"};
        HSSFWorkbook workbook=new HSSFWorkbook();
        HSSFSheet sheet=workbook.createSheet("sheet1");
        HSSFRow row=sheet.createRow(0);
        row.setHeight((short) (15 * 10)); //设置高度
        HSSFCell cell=null;
        HSSFCellStyle style = this.getErrorStyle(workbook);
        for(int i=0;i<ChineseName.length;i++){
            cell=row.createCell(i);

            cell.setCellValue(ChineseName[i]);
        }
        for (int i=0;i<TeamList.size();i++){
            Row nrow=sheet.createRow(i+1);
            for(int j =0;j<FieldName.length;j++)
            {
                Cell ncell=nrow.createCell(j);
                ncell.setCellValue(TeamList.get(i).get(FieldName[j]));
                ncell.setCellStyle(style);
            }

        }
        String FileName = "D:\\code\\IntelIJ IDEA\\GeoLife\\LongHuaVolunteer\\target\\com.ecust\\files\\errormsg\\"+"错误"+filename.substring(0,filename.lastIndexOf("."))+".xls";
        File file1 = new File(FileName);
        if(file1.exists())
        {
            file1.delete();
        }
        FileOutputStream file=new FileOutputStream("D:\\code\\IntelIJ IDEA\\GeoLife\\LongHuaVolunteer\\target\\com.ecust\\files\\errormsg\\"+"错误"+filename.substring(0,filename.lastIndexOf("."))+".xls");
        workbook.write(file);
        file.close();
    }


    public HSSFCellStyle getErrorStyle(HSSFWorkbook workbook) {
        HSSFFont font = workbook.createFont();
        font.setFontName("宋体");
        font.setColor((short) 39);
        HSSFCellStyle style = workbook.createCellStyle();
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);

        style.setBorderTop(BorderStyle.THIN);
        style.setFont(font);
        style.setWrapText(false);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }
}
